<template>
  <div class="productList-container">
    <Search @submit="getTableData" ref="searchBox" />
    <a-button class="product-add-btn" ghost type="primary">
      <RouterLink :to="{ name: 'productAdd' }">添加商品</RouterLink>
    </a-button>
    <ProductTable
      :load="tableLoading"
      :data="tableData"
      @changePager="getTableData"
      @edit="handleEdit"
      @remove="handleRemove"
      ref="table"
    />
  </div>
</template>

<script>
import Search from '@/components/Search.vue';
import ProductTable from '@/components/ProductTable.vue';
import { list, remove } from '@/api/product';

export default {
  components: {
    Search,
    ProductTable,
  },
  data() {
    return {
      tableData: [],
      tableLoading: false,
    };
  },
  methods: {
    async getTableData() {
      this.tableLoading = true;
      const { searchForm, categoryList } = this.$refs.searchBox;
      const { current, pageSize } = this.$refs.table.pager;
      const res = await list({
        page: current,
        size: pageSize,
        ...searchForm,
      });
      // 处理类目
      if (categoryList.length > 0) {
        res.data.forEach((item) => {
          const category = categoryList.find((c) => c.id === item.category);
          const itemC = item;
          if (category) itemC.categoryName = category.name;
        });
      }
      this.$refs.table.pager.total = res.total;
      this.tableData = res.data;
      this.tableLoading = false;
    },
    handleEdit(record) {
      this.$router.push({
        name: 'productEdit',
        params: {
          id: record.id,
        },
      });
    },
    handleRemove(record) {
      this.$confirm({
        title: '确认删除此商品?',
        content: () => <div style="color:red;">{record.title}</div>,
        onOk: async () => {
          await remove(record.id);
          this.$message.success('删除成功！');
          this.getTableData();
        },
        class: 'confirm-box',
        centered: true,
      });
    },
  },
};
</script>

<style lang="less" scoped>
.productList-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .table-container {
    flex: 1 1 0;
  }
  .product-add-btn {
    position: absolute;
    top: 19px;
    right: 30px;
  }
}
</style>
